package com.order.api.service.impl;

import com.order.api.dao.TokenDao;
import com.order.api.po.Token;
import com.order.api.po.TokenExample;
import com.order.api.service.TokenService;
import com.order.api.util.IDGenerator;
import com.order.api.vo.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Value("${token.expiry-time}")
    private Integer TOKEN_EXPIRES_HOUR = 72;

    @Override
    public TokenModel createToken(Long userId) {

        String token = IDGenerator.generator();
        TokenModel model = new TokenModel(userId,token);
        refreshToken(model);
        return model;
    }

    @Override
    public boolean refreshToken(TokenModel model) {
        boolean flag;
        try {
            Date expireTime=getExpireTime();
            int count = tokenDao.replace(Token.builder()
            .token(model.getToken())
            .userId((long) model.getUserId())
            .expireTime(expireTime)
            .updateTime(Calendar.getInstance().getTime())
            .build());
            flag = count == 1;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    @Override
    public boolean checkToken(TokenModel model) {
        if (model == null){
            return false;
        }
        TokenExample example = new TokenExample();
        example.createCriteria()
                .andUserIdEqualTo(model.getUserId())
                .andTokenEqualTo(model.getToken());
        List<Token> list = tokenDao.selectByExample(example);
        if (list == null || list.size() == 0){
            return false;
        }
        Token token = list.get(0);
        if (token.getExpireTime().compareTo(new Date()) <= 0){
            return false;
        }
        refreshToken(model);
        return true;
    }

    private Date getExpireTime(){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR,TOKEN_EXPIRES_HOUR);
        return calendar.getTime();
    }

    @Override
    public TokenModel getToken(String authentication) {
        try {
            if (authentication == null || authentication.length() ==0){
                return null;
            }
            String [] param=authentication.split("_");
            if (param.length != 2){
                return null;
            }
            String userId=param[0];
            String token=param[1];
            return new TokenModel(Long.parseLong(userId),token);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }


    }

    @Override
    public boolean deleteToken(Long userId) {
        boolean flag=true;
        try {
            if (userId !=null){
                TokenExample example = new TokenExample();
                example.createCriteria().andUserIdEqualTo(userId);
                flag = tokenDao.deleteByExample(example) == 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag=false;
        }

        return flag;
    }



}
